# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\licensing\update.py
__author__ = "Attila Gerendi (Sanyi)"
import logging
from sqlalchemy import func as sql_func
from db import Connection
from db.tables.licenses import LicensesTable, LicenseRow
from helpers.licensing.erp import fetch_license

_logger = logging.getLogger("helpers.licensing.update")


def job_update_license(shard, erp_url, license_key):
    try:
        result = fetch_license(erp_url=erp_url, license_key=license_key)
    except Exception as e:
        _logger.exception("update license failed with %s", e)
        return

    with Connection(shard) as (db):
        result["last_refresh"] = sql_func.now()
        q = (
            (LicensesTable.update(values=result))
            .where(LicenseRow.license_key == license_key)
            .returning(LicenseRow.license_key)
        )
        r = db.execute(q).scalar()
        if r is None:
            result["license_key"] = license_key
            q = LicensesTable.insert().values(**result)
            db.execute(q)
    return result
